import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import zhTranslation from './zh.json';
import enTranslation from './en.json';

// 导入翻译文件
const resources = {
  en: {
    translation: enTranslation
  },
  zh: {
    translation: zhTranslation
  }
};

// 从 localStorage 获取保存的语言设置
const getInitialLanguage = () => {
  try {
    const saved = localStorage.getItem('app-settings')
    if (saved) {
      const parsed = JSON.parse(saved)
      return parsed.language || 'zh'
    }
  } catch (error) {
    console.warn('Failed to load language from localStorage:', error)
  }
  
  // 检测系统语言
  if (typeof navigator !== 'undefined' && navigator.language) {
    const lang = navigator.language.toLowerCase()
    if (lang.startsWith('zh')) return 'zh'
    if (lang.startsWith('en')) return 'en'
  }
  
  return 'zh' // 默认语言
};

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: getInitialLanguage(), // 使用动态语言设置
    fallbackLng: 'zh', // 回退语言
    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

export default i18n;